package netty_5;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.ByteBuffer;
import java.util.Scanner;


/**
 * 更高版本的Netty框架
 * */
class ClientHandler extends ChannelHandlerAdapter{


    /**
     * 通道被调用，执行此方法
     * */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //接收数据
//        String value = (String) msg;
        System.out.println("客户端接收到的信息:" + msg);
    }
}


public class Netty_5_Client {

    public static void main(String[] args) throws InterruptedException {
        System.out.println(".....客户端已启动");
        //创建负责接收客户端连接的
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel sc) throws Exception {
                //粘包与拆包
                sc.pipeline().addLast(new FixedLengthFrameDecoder(10));//每10个字符发一次请求
                //以指定的字符拆包
//                ByteBuf buf = Unpooled.copiedBuffer("_li".getBytes("GBK"));
//                sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,buf));
                sc.pipeline().addLast(new StringDecoder());
                sc.pipeline().addLast(new ClientHandler());
            }
        });
        ChannelFuture cf = bootstrap.connect("127.0.0.1",8087);
        //// 当请求频繁时，会自动粘包，然后到客户端进行拆包，此三次因为线程没有睡眠，所已进行了粘包，这三次的数据一起发了过去
        cf.channel().writeAndFlush(Unpooled.wrappedBuffer("libofei".getBytes()));
        cf.channel().writeAndFlush(Unpooled.wrappedBuffer("libofei".getBytes()));
        cf.channel().writeAndFlush(Unpooled.wrappedBuffer("libofei_mayi".getBytes()));
        Thread.sleep(1000);
        cf.channel().writeAndFlush(Unpooled.wrappedBuffer("libofei".getBytes()));
        cf.channel().writeAndFlush(Unpooled.wrappedBuffer("libofei_mayi".getBytes()));
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("请输入内容：");
            cf.channel().writeAndFlush(Unpooled.wrappedBuffer(scanner.next().getBytes()));
        }
        //等待客户端端口号关闭
//        cf.channel().closeFuture().sync();
//        eventLoopGroup.shutdownGracefully();
    }
}
